import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import {
  Empty,
  Button,
  Tooltip,
  Typography,
  Tabs,
  message,
  Spin,
  Pagination,
  Row,
  Col,
  Flex,
  Input,
} from "antd";
import { ReloadOutlined, UserOutlined } from "@ant-design/icons";
import to from "await-to-js";
import {
  getVideoList as getVideoListApi,
  getTabList as getTabListApi,
} from "@/api/search/index";
const { Search } = Input;
const { Paragraph, Text } = Typography;

const Index: React.FC = () => {
  // 获取路由传参
  const { state } = useLocation();
  const navigateTo = useNavigate();
  // 获取视频列表参数
  const getVideoListParams = useRef({
    title: "",
    tagIds: [],
    pageSize: 10,
    pageNum: 1,
    auditState: "1",
    isAsc: "desc",
    orderByColumn: "createTime",
  });

  // 获取标签列表参数
  const getTableListParams = useRef({
    pageSize: 50,
    pageNum: 1,
    auditState: "1",
    isAsc: "desc",
    orderByColumn: "createTime",
  });
  const [videoList, setVideoList] = useState(state.res.rows);
  const [total, setTotal] = useState(state.res.total);
  const [spinning, setSpinning] = useState<boolean>(false);

  const [tabList, setTabList] = useState([]);
  // 获取标签列表
  const getTabList = async () => {
    const [err, res] = await to(getTabListApi(getTableListParams.current));
    if (!err) {
      console.log(res);
      setTabList((tabList) => {
        tabList = res.rows;
        tabList.forEach((item: any) => {
          item.isActive = false;
        });
        return tabList;
      });
      setSpinning(false);
    } else {
      setSpinning(false);
    }
  };
  // 切换页面
  const handlePageChange = async (page, pageSize) => {
    console.log(page, pageSize);
    getVideoListParams.current.pageNum = page;
    getVideoListParams.current.pageSize = pageSize;
    getVideoList();
    // const [err, res] = await to(getVideoListApi(getVideoListParams.current));
    // if (!err) {
    //   console.log(res);
    //   setVideoList((videoList) => {
    //     videoList = res.rows;
    //     return videoList;
    //   });
    //   setTotal((total) => {
    //     total = res.total;
    //     return total;
    //   });
    // }
  };
  // 搜索按钮
  const onSearch = (value: any) => {
    getVideoListParams.current.title = value;
    getVideoList();
  };
  // 挂载时调用
  useEffect(() => {
    getVideoListParams.current.title = state.searchParams.current.title;
    getTabList();
  }, []);
  // tab栏列表
  const items = [
    {
      key: "2",
      label: <span style={{ fontSize: "18px", fontWeight: "600" }}>视 频</span>,
    },
    {
      key: "3",
      label: <span style={{ fontSize: "18px", fontWeight: "600" }}>用 户(开发中)</span>,
    },
  ];
  // 排序方式
  const [sortMode, setSortMode] = useState([
    {
      title: "最多点赞",
      params: "clickCount",
      isActive: true,
    },
    {
      title: "时间排序",
      params: "createTime",
      isActive: false,
    },

    {
      title: "最多评论",
      params: "commentCount",
      isActive: false,
    },
  ]);
  // 获取视频列表
  const getVideoList = async () => {
    setSpinning(true);
    console.log(getVideoListParams.current);
    const [err, res] = await to(getVideoListApi(getVideoListParams.current));
    if (!err) {
      console.log(res);
      setVideoList((videoList) => {
        videoList = res.rows;
        return videoList;
      });
      setTotal((total) => {
        total = res.total;
        return total;
      });
      setSpinning(false);
    } else {
      setSpinning(false);
    }
  };

  // tag是否高亮
  const [isActive, setIsActive] = useState(false);
  // 排序改变按钮
  const handleSortModeChange = (item: any) => {
    const newSort = sortMode.map((subItem: any) => {
      console.log(item.params, subItem.params);
      if (item.params === subItem.params) {
        subItem.isActive = true;
      } else {
        subItem.isActive = false;
      }
      return subItem;
    });
    setSortMode(newSort);
    getVideoListParams.current.orderByColumn = item.params;
    getVideoList();
  };
  // tab改变
  const handleTabChange = () => {};
  // 切换标签
  const handleTagChange = (item: any) => {
    if (item.isActive) {
      item.isActive = false;
      // 删除已勾选的id
      getVideoListParams.current.tagIds =
        getVideoListParams.current.tagIds.filter((subItem) => {
          return subItem != item.tagId;
        });
    } else {
      getVideoListParams.current.tagIds.push(item.tagId);
      item.isActive = true;
    }
    setIsActive(!isActive);
    getVideoList();
  };

  // 视频播放按钮
  const handlePlay = (videoInfo: any) => {
    console.log(videoInfo);
    // 跳转页面并传递参数
    navigateTo("/home/playPage", { state: { videoInfo } });
  };
  return (
    <>
      {/* 搜索框 */}
      <div className="w40%" style={{ margin: "auto", marginTop: "50px" }}>
        <Search
          defaultValue={state.searchParams.current.title}
          onChange={(e) => (getVideoListParams.current.title = e.target.value)}
          placeholder="请输入要检索的内容"
          onSearch={onSearch}
          enterButton
        />
      </div>
      {/* 筛选 */}
      {/* <div>
        <Tabs
          defaultActiveKey="1"
          items={items}
          onChange={handleTabChange}
          indicatorSize={(origin) => origin - 6}
        />
        <div>
          <div>
            <span style={{ fontSize: "14px", fontWeight: "600" }}>排 序：</span>
            {sortMode.map((item) => {
              return (
                <>
                  <Button
                    key={item.params}
                    className="mr-20px"
                    onClick={() => handleSortModeChange(item)}
                    type={item.isActive ? "primary" : "default"}
                  >
                    {item.title}
                  </Button>
                </>
              );
            })}
          </div>
          <div className="mt-20px">
            <span style={{ fontSize: "14px", fontWeight: "600" }}>标 签：</span>
            {tabList.map((item) => {
              return (
                <>
                  <Button
                    key={item.tagId}
                    className="mr-20px"
                    onClick={() => handleTagChange(item)}
                    type={item.isActive ? "primary" : "default"}
                  >
                    {item.content}
                  </Button>
                </>
              );
            })}
          </div>
        </div>
      </div> */}
      <Spin tip="Loading" size="large" spinning={spinning}>
        {/* 视频列表 */}
        {videoList.length > 0 && (
          <div className="flex flex-wrap">
            {videoList.map((item: any) => {
              return (
                <div key={item.videoId} className="cursor-pointer">
                  <div
                    onClick={() => handlePlay(item)}
                    className="mr-29px mt-40px w235px h145px mb-5px"
                    style={{
                      borderRadius: "2%",
                      border: "1px solid #999",
                    }}
                  >
                    <img
                      src={item.images ?? ""}
                      alt=""
                      className="absolute w-233px h-144px object-contain"
                      style={{ borderRadius: "3%" }}
                    />
                    <Tooltip title="开始播放">
                      <img
                        style={{
                          width: "40px",
                          height: "40px",
                          marginLeft: "100px",
                          marginTop: "54px",
                        }}
                        className="absolute  cursor-pointer"
                        src={"bigplay.png"}
                        alt=""
                      />
                    </Tooltip>
                  </div>
                  <Paragraph
                    ellipsis={{ rows: 1, expandable: false }}
                    className=" w240px h-20px"
                    style={{
                      lineHeight: "20px",
                      fontWeight: "600",
                      color: "#444",
                    }}
                  >
                    {item.title}
                  </Paragraph>
                  <div
                    className=" mt--10px mb-10px"
                    style={{ color: "#666", fontSize: "14px" }}
                  >
                    <span>
                      <UserOutlined />
                      {item.createBy}
                    </span>
                    <span className="ml-20px">{item.createTime}</span>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {videoList.length === 0 && <Empty />}

        {/* <Pagination
          showQuickJumper
          defaultCurrent={1}
          total={total}
          onChange={handlePageChange}
        /> */}
        <div className="mt-20px" style={{ margin: "auto" }}>
          {total > 0 && (
            <Pagination
              total={total}
              showSizeChanger
              showQuickJumper
              showTotal={(total) => `总共 ${total} 项`}
              onChange={handlePageChange}
            />
          )}
        </div>
      </Spin>
    </>
  );
};

export default Index;
